/**
 * 移动拖拽元素
 * @param {queryElementCallback} Function 返回一个目标元素
 * @param {moveCallback} Function 移动时触发
 * @param {option} Object 可选参数
 * @returns {Object}
 */
export default (targetEl, moveCallback, option = {}) => {
    let dragging = false;
    let tLeft = 0;
    let tTop = 0;

    option = {
        disableX: false,
        disableY: false,
        ...option,
    };

    const touchStart = (e) => {
        const touch = e.touches?.[0] || e.targetTouches?.[0];

        if (!touch) return;

        dragging = true;

        tLeft = touch.clientX - targetEl.offsetLeft;
        tTop = touch.clientY - targetEl.offsetTop;
    };

    const touchMove = e => {
        e.preventDefault();
        e.stopPropagation();

        const moveTouch = e.touches[0];
        let moveX = moveTouch.clientX - tLeft;
        let moveY = moveTouch.clientY - tTop;

        if (moveX <= 0) {
            moveX = 0;
        }

        if (moveX + targetEl.offsetWidth >= window.outerWidth) {
            moveX = window.outerWidth;
        }

        if (moveY <= 0) {
            moveY = 0;
        }

        if (moveY + targetEl.offsetHeight >= window.outerHeight) {
            moveY = window.outerHeight;
        }

        moveCallback({
            moveX,
            moveY,
            target: targetEl,
        });
    };

    const touchEnd = () => {
        dragging = false;
    };

    const bodyTouchMove = (e) => {
        if (dragging) {
            e.preventDefault();
        }
    };

    targetEl.addEventListener('touchstart', touchStart);
    targetEl.addEventListener('touchmove', touchMove);
    targetEl.addEventListener('touchend', touchEnd);
    document.body.addEventListener('touchmove', bodyTouchMove, { passive: false });

    return {
        destroy() {
            targetEl.removeEventListener('touchstart', touchStart);
            targetEl.removeEventListener('touchmove', touchMove);
            targetEl.removeEventListener('touchend', touchEnd);
            document.body.removeEventListener('touchmove', bodyTouchMove);
        }
    };
};
